<template>
  <div class="image-block">
    <!-- 编辑模式 -->
    <div v-if="!previewMode" class="image-editor">
      <el-form label-position="top" size="small">
        <!-- 图片上传区域 -->
        <el-form-item label="图片">
          <div class="image-upload-area">
            <!-- 已有图片预览 -->
            <div v-if="localContent.src || imagePreviewUrl" class="image-preview-container">
              <img 
                :src="imagePreviewUrl || localContent.src" 
                :alt="localContent.alt" 
                class="preview-image"
              />
              <div class="image-actions">
                <el-upload
                  ref="imageUploadRef"
                  :auto-upload="false"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                  :on-change="handleImageChange"
                  accept="image/png,image/jpeg,image/jpg,image/gif,image/svg+xml,image/webp"
                >
                  <el-button type="primary" size="small">
                    <el-icon><Upload /></el-icon>
                    更换图片
                  </el-button>
                </el-upload>
                <el-button type="danger" size="small" @click="removeImage">
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </div>
            </div>
            
            <!-- 无图片时的上传区域 -->
            <div v-else class="upload-placeholder">
              <el-upload
                ref="imageUploadRef"
                :auto-upload="false"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-change="handleImageChange"
                accept="image/png,image/jpeg,image/jpg,image/gif,image/svg+xml,image/webp"
                class="upload-dragger"
                drag
              >
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击或拖拽上传图片</div>
                <div class="upload-hint">支持 PNG、JPG、GIF、SVG、WebP 格式，最大 5MB</div>
              </el-upload>
            </div>
          </div>
        </el-form-item>
        
        <!-- 图片URL输入（备选方案） -->
        <el-form-item label="或输入图片链接">
          <el-input
            v-model="localContent.src"
            placeholder="请输入图片URL"
            @input="handleUrlInput"
          />
        </el-form-item>
        
        <el-form-item label="图片描述">
          <el-input
            v-model="localContent.alt"
            placeholder="请输入图片描述"
            @input="handleUpdate"
          />
        </el-form-item>
        
        <!-- 图片文本内容 -->
        <el-form-item label="图片说明文本">
          <el-input
            v-model="localContent.caption"
            type="textarea"
            :rows="3"
            placeholder="请输入图片说明文本（可选）"
            @input="handleUpdate"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 预览模式 -->
    <div v-else class="image-preview">
      <div class="image-container">
        <img 
          v-if="localContent.src"
          :src="localContent.src"
          :alt="localContent.alt"
          class="preview-image"
        />
        <div v-else class="image-placeholder">
          <el-icon size="48" color="#ddd"><Picture /></el-icon>
          <p>暂无图片</p>
        </div>
        
        <!-- 图片说明文本 -->
        <div v-if="localContent.caption" class="image-caption">
          {{ localContent.caption }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Upload, Delete, Plus } from '@element-plus/icons-vue'
import apiService from '@/services/api'

// Props
const props = defineProps({
  block: {
    type: Object,
    required: true
  },
  previewMode: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update'])

// 响应式数据
const imageUploadRef = ref()
const imagePreviewUrl = ref('')
const imageFile = ref(null)
const isUploading = ref(false)

// 本地内容状态
const localContent = ref({
  src: '',
  alt: '图片描述',
  caption: '',
  ...props.block.content
})

/**
 * 图片上传前的验证
 */
const beforeImageUpload = (file) => {
  const isValidType = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/svg+xml', 'image/webp'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('图片格式不正确！支持 PNG、JPG、GIF、SVG、WebP 格式')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

/**
 * 处理图片文件选择
 */
const handleImageChange = async (file) => {
  if (!beforeImageUpload(file.raw)) {
    return
  }
  
  imageFile.value = file.raw
  
  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
  
  // 上传图片到服务器
  await uploadImageToServer(file.raw)
}

/**
 * 上传图片到服务器
 */
const uploadImageToServer = async (file) => {
  try {
    isUploading.value = true
    
    // 创建FormData
    const formData = new FormData()
    formData.append('image', file)
    formData.append('alt', localContent.value.alt || '富文本编辑器图片')
    formData.append('caption', localContent.value.caption || '')
    
    // 调用专用的图片上传API
    const response = await apiService.items.uploadImage(formData)
    
    if (response && response.data && response.data.url) {
      // 更新图片URL
      localContent.value.src = response.data.url
      imagePreviewUrl.value = ''
      handleUpdate()
      ElMessage.success('图片上传成功')
    } else {
      throw new Error('上传响应格式错误')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
    // 清除预览
    imagePreviewUrl.value = ''
    imageFile.value = null
  } finally {
    isUploading.value = false
  }
}

/**
 * 移除图片
 */
const removeImage = () => {
  localContent.value.src = ''
  imagePreviewUrl.value = ''
  imageFile.value = null
  if (imageUploadRef.value) {
    imageUploadRef.value.clearFiles()
  }
  handleUpdate()
}

/**
 * 处理URL输入
 */
const handleUrlInput = () => {
  // 如果用户输入了URL，清除上传的文件预览
  if (localContent.value.src) {
    imagePreviewUrl.value = ''
    imageFile.value = null
    if (imageUploadRef.value) {
      imageUploadRef.value.clearFiles()
    }
  }
  handleUpdate()
}

/**
 * 处理内容更新
 */
const handleUpdate = () => {
  emit('update', {
    ...props.block,
    content: { ...localContent.value }
  })
}

// 监听 props 变化
watch(() => props.block.content, (newContent) => {
  localContent.value = { ...localContent.value, ...newContent }
}, { deep: true })
</script>

<style scoped>
.image-block {
  width: 100%;
}

.image-editor {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.image-upload-area {
  width: 100%;
}

.image-preview-container {
  position: relative;
  display: inline-block;
  max-width: 100%;
}

.image-preview-container .preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview-container:hover .image-actions {
  opacity: 1;
}

.upload-placeholder {
  width: 100%;
}

.upload-dragger {
  width: 100%;
}

.upload-dragger :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafbfc;
  transition: all 0.3s ease;
}

.upload-dragger :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

.image-preview {
  width: 100%;
}

.image-container {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  background: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  color: #999;
}

.image-placeholder p {
  margin-top: 12px;
  font-size: 14px;
}

.image-caption {
  margin-top: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  text-align: left;
}

/* 加载状态 */
.uploading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}
</style>